<template>
  <div class="pay-container">
    <div class="pay-header">
      <h1>收银台</h1>
      <div class="amount">
        <span class="currency">¥</span>
        <span class="number">{{ fee }}元</span>
      </div>
    </div>

    <div class="pay-content">
      <div class="order-info">
        <div class="info-item">
          <span class="label">合同编号：</span>
          <span class="value">{{ orderId }}</span>
        </div>
        <div class="info-item">
          <span class="label">合同金额：</span>
          <span class="value">{{ amount }}元</span>
        </div>
      </div>

      <div class="payment-action">
        <u-button type="primary" @click="handlePayment" :disabled="!payReady">{{ isLoading ? '支付中...' : '立即支付' }}</u-button>
      </div>
    </div>
  </div>
</template>

<script>
import wechat from '@/utils/wechat.js'
import {apiConfig} from '@/utils/apiConfig'
import { getSocialLogin, createPayOrder, createWeixinJsapiSignature, getContractDetails } from '@/api/user'
export default {
  name: 'PayPage',
  data() {
    return {
      amount: '',
      fee: '',
      orderId: '',
      isLoading: false,
      paymentParams: {},
      payReady: false,
      contractId: '',
    }
  },
  onLoad(options) {
    this.contractId = uni.getStorageSync('contractId')
    const orderId = uni.getStorageSync('orderId')
    getContractDetails({contractId: this.contractId}).then(res => {
      console.log(res)
      this.fee = res.data.data.fee
      this.amount = res.data.data.amount
      this.orderId = res.data.data.contractNo
    })
    this.checkUrlParams()
  },
  methods: {
    async getJSSDKConfig() {
      try {
        const res = await createWeixinJsapiSignature({url: apiConfig.webUrl})
        return res.data.data
      } catch (error) {
        console.error('获取JSSDK配置失败', error)
        throw error
      }
    },
    async handlePayment() {
      try {
        const jssdkConfig = await this.getJSSDKConfig()
        await wechat.initJSSDK(jssdkConfig)
        console.log('paymentParams', this.paymentParams)
        const res = await wechat.requestPayment(this.paymentParams)
        console.log('支付成功', res)

        uni.showToast({
          title: '支付成功',
          icon: 'success'
        })
        uni.navigateTo({
          url: '/pages/contract/detail?id=' + this.contractId
        })
      } catch (error) {
        this.handlePayment()
      }
    },
    checkUrlParams() {
      const query = {};
      const url = window.location.href;
      console.log('url', url)
      // 解析查询参数
      const searchPart = url.split('?')[1];
      if (searchPart) {
        const searchParams = searchPart.split('&');
        searchParams.forEach(param => {
          const [key, value] = param.split('=');
          if (key) query[key] = decodeURIComponent(value || '');
        });

        // 检查是否有code参数
        if (query.code && query.state) {
          this.getOpenidByCode(query.code, query.state || '');
        } else if (query.error) {
          this.statusText = '授权失败: ' + query.error;
        }
      }
    },
    getOpenidByCode(code, state) {
      const orderId = uni.getStorageSync('orderId')
      if (!orderId) {
        uni.showToast({
          title: '订单号不存在',
          icon: 'none'
        })
        return
      }
      getSocialLogin({
        type: 31,
        code: code,
        state: state || ''
      }).then(res => {
        const openid = res.data.data.openid
        createPayOrder({
          id: orderId,
          channelCode: 'wx_pub',
          channelExtras: {
            openid: openid
          }
        }).then(res => {
          console.info(JSON.parse(res.data.data.displayContent))
          const displayContent = JSON.parse(res.data.data.displayContent)
          this.paymentParams = {appId: displayContent.appId, timeStamp: displayContent.timeStamp, nonceStr: displayContent.nonceStr, package: displayContent.packageValue, signType: displayContent.signType, paySign: displayContent.paySign}
          this.payReady = true
        }).catch(err => {
          console.info('error', err)
          setTimeout(() => {
            uni.switchTab({
              url: '/pages/contract/index'
            })
          }, 2000)
        })
      })
    },
  }
}
</script>

<style scoped>
.pay-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  background: #fff;
  min-height: 100vh;
}

.pay-header {
  text-align: center;
  padding: 20px 0;
  border-bottom: 1px solid #eee;
}

.pay-header h1 {
  color: #333;
  font-size: 24px;
  margin-bottom: 20px;
}

.amount {
  font-size: 40px;
  color: #333;
  font-weight: bold;
}

.currency {
  font-size: 24px;
  margin-right: 4px;
}

.pay-content {
  padding: 40px 20px;
}

.order-info {
  background: #f8f8f8;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 40px;
}

.info-item {
  display: flex;
  margin-bottom: 12px;
  font-size: 14px;
  line-height: 1.5;
}

.info-item:last-child {
  margin-bottom: 0;
}

.label {
  color: #666;
  width: 80px;
}

.value {
  color: #333;
  flex: 1;
}

.payment-action {
  text-align: center;
}

.pay-button {
  background: #07c160;
  color: white;
  border: none;
  border-radius: 8px;
  padding: 12px 40px;
  font-size: 16px;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.pay-button:disabled {
  background: #9fd7b5;
  cursor: not-allowed;
}

.pay-button:not(:disabled):hover {
  background: #06ae56;
}

.wechat-icon {
  width: 20px;
  height: 20px;
  margin-right: 8px;
}
</style>
